/*
 * Modes:
 *  0. joining
 *  1. chooseFrom
 *  2. chooseTo
 *  3. victoryA
 *  4. victoryB
 */

var title;

/*
var analytics;
analytics = new _IG_GA("UA-11145256-1");
analytics.reportPageview('/tilegrab/click/startGame');
*/

// Document initialize.
$(function(){
	title = document.getElementById('gadget_title');
});

function startGame() {
	try {
		var tiles = Board.setupTiles();
		var moves = Board.setupNoLegalMoves();
		var goals = Board.setupGoals();
		submitData({
			'tiles': encode(tiles),
			'mode': encode('joining'),
			'fromRow': encode(-1),
			'fromCol': encode(-1),
			'turn': encode(-1),
			'moves': encode(moves),
			'goals': encode(goals),
			'playerA': encode(-1),
			'playerB': encode(-1)
		});
	}
	catch (e) {
		Error.show('startGame', e);
	}
}

function stateUpdated() {
	try {
		generatePlayerList();
		generateGameBoard();
		generateStatus();
		gadgets.window.adjustHeight();
	}
	catch (e) {
		alert('Error in stateUpdated()\n' + e);
	}
}

function generateGameBoard() {
	var h = '<table>';
	
	var tiles = getData('tiles');
	var moves = getData('moves');
	var goals = getData('goals');
	
	for (i = 0; i < tiles.length; i++)
	{
		h += '<tr>';
		
		row = tiles[i];
		for (j = 0; j < row.length; j++) {
			
			var spaceClass = '';
			var pieceClass = row[j];
			
			if (moves != null && moves.length > 0 && moves[i][j] == true)
			{
				spaceClass += ' possible';
				pieceClass += ' possible';
			}
			
			if (goals != null && goals.length > 0) {
				if (goals[i][j] == 'a') {
					spaceClass += ' redVictory';
				}
				else if (goals[i][j] == 'b') {
					spaceClass += ' blueVictory';
				}
			}
			
			h += '<td class="' + spaceClass + '" onclick="spaceClick('+ i + ',' + j + ')">';
			h += '<div class="' + pieceClass + '">&nbsp;</div>';
			h += '</td>';
		}
		
		h += '</tr>';
	}
	h += '</table>';
	
	$('#gameBoard').html(h);
}

function generateStatus() {
	var s = '';
	var mode = getData('mode');
	
	switch (mode) {
		case 'joining':
			s = 'Waiting for players to join...';
			break;
		case 'chooseFrom':
			s = 'Choose a piece to move.';
			break;
		case 'chooseTo':
			s = 'Choose a location to move your piece to.';
			break;
		case 'victoryA':
			s = 'The red player has won!';
			break;
		case 'victoryB':
			s = 'The blue player has won!';
			break;
	}
	
	$('#status').text(s);
}

function generatePlayerList() {
	var t = '';
	var mode = getData('mode');
	var a = getData('playerA');
	var b = getData('playerB');
	var currentPlayerLetter = getCurrentPlayerLetter();
	var turn = getData('turn');
	
	t += '<table>';
	if (turn === 'a') {
		t += '<tr class="currentPlayer">';
	}
	else {
		t += '<tr>';
	}
	t += '<td class="red">Red Player: </td><td>';
	
	if (mode == 'joining' && a === -1 && currentPlayerLetter == 'x') {
		t += '<input type="button" value="Join as Red Player!" id="buttonJoinAsRed" onclick="join(\'a\')" />'
	}
	else {
		var playerName = wave.getParticipantById(a);
		if (playerName != null) {
			t += playerName.getDisplayName();
		}
	}
	
	t += '</td></tr>';
	if (turn === 'b') {
		t += '<tr class="currentPlayer">';
	}
	else {
		t += '<tr>';
	}
	t += '<td class="blue">Blue Player: </td><td>';
	
	if (mode == 'joining' && b === -1 && currentPlayerLetter == 'x') {
		t += '<input type="button" value="Join as Blue Player!" id="buttonJoinAsBlue" onclick="join(\'b\')" />'
	}
	else {
		var playerName = wave.getParticipantById(b);
		if (playerName != null) {
			t += playerName.getDisplayName();
		}
	}
	
	t += '</td></tr>';
	t += '</table>';
	$('#playerList').html(t);
}

function join(playerLetter) {
	try {
		var currentUserId = wave.getViewer().getId();
		var stateKey = '';
		var otherStateKey = '';
		var submission = {};
		
		if (playerLetter == 'a') { 
			stateKey = 'playerA';
			otherStateKey = 'playerB';
		}
		else {
			stateKey = 'playerB';
			otherStateKey = 'playerA';
		}
		
		// Figure out if both players have joined.
		var otherPlayerId = getData(otherStateKey);
		if (otherPlayerId !== -1) {
			submission['mode'] = encode('chooseFrom');
			submission['turn'] = encode('a');
		}
		
		submission[stateKey] = encode(currentUserId);
		submitData(submission);
	}
	catch (e) {
		alert('Error in join(): ' + e);
	}
}

function getCurrentPlayerLetter() {
	var currentUserId = wave.getViewer().getId();
	var playerA = getData('playerA');
	var playerB = getData('playerB');
	
	if (currentUserId == playerA) {
		return 'a';
	}
	else if (currentUserId == playerB) {
		return 'b';
	}
	else {
		return 'x';
	}
}

function spaceClick(i, j) {
	try {
		var playerLetter = getCurrentPlayerLetter();
		var turn = getData('turn');
		
		if (playerLetter != turn) {
			return;
		}

		var mode = getData('mode');
		var tiles = getData('tiles');
		
		if (mode == 'chooseFrom') {
			if (Board.isLegalMoveStart(playerLetter, tiles, i, j)) {
				var moves = Board.setupLegalMoves(tiles, i, j);
				
				submitData({
					'mode': encode('chooseTo'),
					'fromRow': encode(i),
					'fromCol': encode(j),
					'moves': encode(moves)
				});
			}
		}
		else if (mode == 'chooseTo') {
			var fromRow = getData('fromRow');
			var fromCol = getData('fromCol');
			var newMoves = Board.setupNoLegalMoves();
			
			if (Board.isLegalMoveEnd(tiles, fromRow, fromCol, i, j)) {
				var goals = getData('goals');
				tiles = Board.makeMove(tiles, fromRow, fromCol, i, j);

				if (Board.isVictory(tiles, goals)) {
					var newMode;
					if (turn == 'a') {
						newMode = 'victoryA';
					}
					else {
						newMode = 'victoryB';
					}
					
					submitData({
						'mode': encode(newMode),
						'tiles': encode(tiles),
						'moves': encode(newMoves)
					});
				}
				else {
					// Prepare the board for the chooseFrom mode
					
					var newTurn;
					if (turn == 'a') newTurn = 'b';
					else if (turn == 'b') newTurn = 'a';
					
					submitData({
						'mode': encode('chooseFrom'),
						'tiles': encode(tiles),
						'turn': encode(newTurn),
						'moves': encode(newMoves)
					});
				}
			}
		}
	}
	catch (e) {
		alert('Error in spaceClick(): ' + e);
	}
}

// Note: registration must happen after function is defined.
function init() {
	try {
    	if (wave && wave.isInWaveContainer()) {
      		wave.setStateCallback(stateUpdated);
    	}
	}
	catch (e) {
		alert('Error in init()\n' + e);
	}
}
gadgets.util.registerOnLoadHandler(init);

function isHost() {
	var currentUserId = wave.getViewer().getId();
	var hostUserId = wave.getHost().getId();
	return currentUserId == hostUserId;
}

function getData(key) {
	var dataJson = wave.getState().get(key, "{}");
	return gadgets.json.parse(dataJson);
}

function encode(nonJson) {
	return gadgets.json.stringify(nonJson);
}

function submitData(dict) {
	wave.getState().submitDelta(dict);
}
